package com.symbio.ishenapi.background.controller;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.symbio.ishenapi.background.model.*;
import com.symbio.ishenapi.common.bean.LoginUser;
import com.symbio.ishenapi.common.controller.BaseController;
import io.jboot.web.controller.annotation.RequestMapping;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/TmPatientUser")
public class TmPatientUserController extends BaseController {

    /**
     * wy:患者管理
     *    修改之回显
     */
    public void findOnePatient(){
        TmPatientUser user = (TmPatientUser) getReqBodyObject(TmPatientUser.class);
        if (user.getId() == null && "".equals(user.getId())){
            renderJsonError(500002);
            return;
        }
        renderJsonRet(user.findById(user.getId()));
    }


    public void findOneTmPatientUser(){       //显示一个患者信息
        String  id = getPara("id");
        if (id != null && !"".equals(id)){
            TmPatientUser item = TmPatientUser.dao.findById(new BigInteger(id));
            if (item != null ) {
                renderJsonRet(item);
                return;
            }
            renderJsonError(40003,"该用户信息为空");
            return;
        }
    }



    /**
     * wy:患者管理
     *    修改
     */
    public void updatePatient(){
        TmPatientUser user = (TmPatientUser) getReqBodyObject(TmPatientUser.class);
        TmPatientUser patientUser = user.findById(user.getId());
        List<TmPatientUser> list = user.findTmPatientUserByPhone(patientUser);
        if (user.getUserState() == "1" || "1".equals(user.getUserState())){
            if (list.size() > 1){
                System.out.println("表中已经存在同手机号的数据.");
                renderJsonError(50002, "重复数据,修改");
                return;
            }
        }

        if (user.update()) {
            renderJsonRet(user.getId());
            return;
        } else {
            renderJsonError(50002, "修改");
            return;
        }
    }


    public void updTmPatientUser(){         //修改患者信息
        System.out.println("进入修改患者信息方法");
        TmPatientUser user = (TmPatientUser) getReqBodyObject(TmPatientUser.class);
        if(user.getId()==null || "".equals(user.getId())){
            renderJsonError(40003,"id");
        }
        TmPatientUser u = TmPatientUser.dao.findById(user.getId());
        if (u!=null) {
            System.out.println("数据库中用户信息不为空"+u.getUserMobilePhone());
            if (!StrKit.isBlank(user.getUserName())) u.setUserName(user.getUserName());
            if (!StrKit.isBlank(user.getUserEmail())) u.setUserEmail(user.getUserEmail());
            if (!StrKit.isBlank(user.getUserNickName())) u.setUserNickName(user.getUserNickName());
            if (!StrKit.isBlank(user.getUserSex())) u.setUserSex(user.getUserSex());
            if (!StrKit.isBlank(user.getUserCity())) u.setUserCity(user.getUserCity());
            if (!StrKit.isBlank(user.getUserIdCard())) u.setUserIdCard(user.getUserIdCard());
            if(!StrKit.isBlank(user.getUserIdCardType())){
                u.setUserIdCardType(user.getUserIdCardType());
            }
            if(!StrKit.isBlank(user.getUserSource())){
                if("0".equals(user.getUserSource())){
                    u.setUserSource("门诊患者");
                }else if("1".equals(user.getUserSource())){
                    u.setUserSource("病房患者");
                }else if("2".equals(user.getUserSource())){
                    u.setUserSource("其他来源");
                }

            }
            if (!StrKit.isBlank(user.getUserBirthday())){
                u.setUserBirthday(user.getUserBirthday());
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date birthday=null;
                try{
                    birthday=format.parse(user.getUserBirthday());
                }catch (Exception e){

                }

                int age = 0;
                Date now = new Date();
                SimpleDateFormat format_y = new SimpleDateFormat("yyyy");
                SimpleDateFormat format_M = new SimpleDateFormat("MM");
                String birth_year =format_y.format(birthday);
                String this_year = format_y.format(now);

                String birth_month = format_M.format(birthday);
                String this_month =format_M.format(now);

                // 初步，估算
                age = Integer.parseInt(this_year) - Integer.parseInt(birth_year);

                // 如果未到出生月份，则age - 1
                if(this_month.compareTo(birth_month) < 0){
                    age -= 1;
                }
                if (age < 0){
                    age =  0;
                }
                System.out.println("age"+age);
                u.setUserAge(String.valueOf(age));
            }

            if (!StrKit.isBlank(user.getUserDetailedAddress())) u.setUserDetailedAddress
                    (user.getUserDetailedAddress());
            if (!StrKit.isBlank(user.getUserPostCode())) u.setUserPostCode(user.getUserPostCode());
            if (!StrKit.isBlank(user.getUserHeadPortrait())) u.setUserHeadPortrait(user.getUserHeadPortrait
                    ());
            if (u.update()) {
                renderJsonRet(user.getId());
            } else {
                renderJsonError(40005);
                return;
            }
        }else{
            System.out.println("数据库中用户信息为空");
            renderJsonError(40003);
            return;
        }


    }



    /**
     * wy:患者管理
     *    批量禁用
     */
    public void delPatient(){
        String ids = getReqBodyString().replace("\"","").replace("\"","");
        TmPatientUser tpu = new TmPatientUser();
        if (tpu.delPatient(ids)) {
            renderJsonRet(500001);
        }else {
            renderJsonError(500002,"禁用");
        }
    }

    /**
     * wy:根据条件分页查询患者
     */
    public void findConditionPatientList(){       //根据条件查询显示患者列表
        String userName = getPara("userName");

        LoginUser loginUser = getLoginUser();
        String Ids = loginUser.getDoctorIds();
        if (Ids != null && !"".equals(Ids)) {
            if (Ids.endsWith(",")) {
                Ids = Ids.substring(0, (Ids.length() - 1));
            }
        }
        Map map = TmPatientUser.dao.findConditionPatientList(getQueryModel(),userName,Ids);
        renderPageJsonRet(map.get("count"),map.get("data"));
    }


    /**
     * @Author GuoShunYou
     * @Description id(用户id)、insuanCorpsId保险团id 查询是否为保险团用户，并且匹配保险团险种  是否可以关注保险团
     * @date 上午 11:38   2018/11/1
     * @return void
     */
    public void  isnoinsurance(){
        TmInsurancorpsUser tm = (TmInsurancorpsUser) getReqBodyObject(TmInsurancorpsUser.class);
        TmPatientUser user=TmPatientUser.dao.isInsuranUser(tm.getId());
        if(user==null){
            renderJsonError(40016,"该用户");
            return;
        }
        if("1".equals(user.getIsNoinsurance())){
            //通过userid查询所关联的险种id
            TmInsuantypeUser inuser=TmInsuantypeUser.dao.getinsuraId(tm.getId());
            if(inuser==null){
                renderJsonError(50004,"险种匹配保险团失败、不可关注");
                return;
            }
            Long a=inuser.getInsuranTypeId();



            //通过保险团id查询所关联的险种id
            TmInsurantypeCorps titc=TmInsurantypeCorps.dao.getTypeId(tm.getInsuanCorpsId());

            if(titc==null){
                renderJsonError(50004,"险种匹配保险团失败、不可关注");
                return;
            }
            Long b=titc.getInsuranTypeId();


            //匹配险种
            if(a==b){
                renderJsonError(50003,"可以关注");
            }else {
                renderJsonError(50004,"不可关注");
            }
        }else{
            renderJsonError(50004,"该用户不是保险团用户、不可关注");
            return;
        }
    }

    /**
     * @Author GuoShunYou
     * @Description 通过多个userid查询对应的患者信息
     * @date 下午 8:43   2018/11/10
     * @return void
     */
    public void getuserByid(){
        TmPatientUser tm = (TmPatientUser) getReqBodyObject(TmPatientUser.class);
        List<TmPatientUser> list=TmPatientUser.dao.getlistuse(tm.getUserType());
        renderJsonRet(list);



    }

    /**
     * 患者基本信息查询
     **/
    public  void patientXx(){
        //TmPatientUser tm =(TmPatientUser)getReqBodyObject(TmPatientUser.class);
        String userId = getPara("userId");
        renderJsonRet(TmPatientUser.dao.finduser(new BigInteger(userId)));
    }

    /*患者基本信息添加*/
    public void patientSave() {
        TmPatientUser tm = (TmPatientUser) getReqBodyObject(TmPatientUser.class);
        Date date =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
        String time = sdf.format(date);
        tm.setCreateTime(time);
        if (tm !=null) {
            renderJsonRet(40001);
        }else{
            renderJsonError(40003,"患者基本");
        }
    }

    public void patientList(){  //患者列表
        TmPatientUser tmPatientUser=(TmPatientUser)getReqBodyObject(TmPatientUser.class);
        List<TmPatientUser> list=TmPatientUser.dao.findPatient();
        renderJsonRet(list);
    }


    /**
     * @Author GuoShunYou
     * @Description 通过userid、doctorid解绑患者医生关联
     * @date 下午 9:32   2018/11/8
     * @return void
     */
    public void delUserDoctor(){
        TmPatientDoctor tm = (TmPatientDoctor) getReqBodyObject(TmPatientDoctor.class);
        TmPatientDoctor tmdd=TmPatientDoctor.dao.delpatientdotor(tm);
        boolean b=tmdd.delete();
        if(b){
            renderJsonError(50001,"解绑关注");
        }else{
            renderJsonError(50001,"解绑关注");
        }


    }

    /**
     * 多个患者基本信息查询
     */
    public  void findUserIds(){
        String userIds = getReqBodyString();
        System.out.println(userIds);
        List<TmPatientUser> users = TmPatientUser.dao.findUserIds(userIds);
        if (users.size() > 0){
            renderJsonRet(users);
        }else {
            renderError(40003,"关联");
        }
    }



    /**
     * wy:患者端
     *    通过患者ID查询医生和保险团基本信息
     */
    public  void findUserIdByDoctorAndInsurance(){
        String userId = getPara("userId");
        List<Record> doctor = TmDoctorUser.dao.findUserIdByDoctorAndInsurance(userId);
        List<Record> insurance = TmInsuranceCorps.dao.findUserIdByDoctorAndInsurance(userId);
        //Map map = new HashMap();
        for (int i = 0; i < insurance.size(); i++ ){
            doctor.add(insurance.get(i));
        }
        //map.put("data",doctor);
        renderJsonRet(doctor);
    }

    /**
     * wy:后台
     *    通过患者ID查询保险团基本信息
     */
    public  void findUserIdByInsurance(){
        String userId = getPara("id");
        Map map = TmInsuranceCorps.dao.findUserIdByInsurance(getQueryModel(),userId);
        renderPageJsonRet(map.get("count"),map.get("data"));
    }

    /** GET
     * @Author: chen
     * @Description:多患者查询
     * @Date: 18:42 2018/11/26
     * @param: "1215,1216,1219"
     * @return: void
     */
    public void findMorePatientUser(){
        try {
            String ids = getPara("ids");
            List<Record> data = TmPatientUser.dao.findMorePatientUser(ids);
            renderJsonRet(data);
        }catch (Exception e){
            renderJsonError(50002,"多患者查询");
        }
    }

    /** GET
     * @Author: chen
     * @Description:医生端群组添加患者列表查询
     * @Date: 16:01 2018/12/4
     * @param: [
     *              doctorId   ---医生id
     *              groupId ---群组id
     *          ]
     * @return: void
     */
    public void findGroupMembersByHostId(){
        try {
            String userSource = getPara("userSource");
            String doctorId = getPara("doctorId");
            String groupId = getPara("groupId");
            List<TmPatientUser> data = TmPatientUser.dao.findGroupMembersByHostId(userSource,doctorId,groupId);
            renderJsonRet(data);
        }catch (Exception e){
            e.printStackTrace();
            renderJsonError(50002,"群组添加患者列表查询");
        }
    }

    /**
     * wy:患者端
     * 根据医生ID,患者ID查询患者和医生基本信息
     */
    public void findByIdToDidAndPid(){
        String doctorId = getPara("doctorId");
        String patientId = getPara("patientId");
        TmPatientUser patientUser = TmPatientUser.dao.findById(patientId);
        TmDoctorUser doctorUser = TmDoctorUser.dao.findById(doctorId);
        Map map = new HashMap();
        if (patientUser != null && !"".equals(patientUser) && doctorId != null && !"".equals(doctorId)){
            map.put("doctor",doctorUser);
            map.put("patient",patientUser);
            renderJsonRet(map);
            return;
        }else {
            renderJsonError(50002,"查询");
            return;
        }
    }
}
